package com.dily.study.work.service;

import com.dily.study.work.entity.User;
import com.dily.study.work.repository.UserRepository;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Date: 2022-08-08 星期一
 * Time: 17:02
 * Author: Dily_Su
 * Remark:
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 转出
     *
     * @param fromName 从谁转出
     * @param money    转出金额
     */
    public void out(String fromName, int money) {
        User user = userRepository.findByName(fromName);
        user.setMoney(user.getMoney() - money);
        userRepository.save(user);
    }

    /**
     * 转入
     *
     * @param toName 转到哪里
     * @param money  转入金额
     */
    public void in(String toName, int money) {
        User user = userRepository.findByName(toName);
        user.setMoney(user.getMoney() + money);
        userRepository.save(user);
    }


    /**
     * 带事务
     * 要么都成功，要么都失败
     *
     * @param fromName 从哪里转出
     * @param toName   转入到哪里
     * @param money    金额
     */
    @Transactional
    public void transfer(String fromName, String toName, int money) {
        out(fromName, money);
        if (true) throw new RuntimeException("出错了");
        in(toName, money);
    }


    /**
     * 不带事务
     * 只有转出成功，转入失败
     *
     * @param fromName 从哪里转出
     * @param toName   转入到哪里
     * @param money    金额
     */
//    public void transfer(String fromName, String toName, int money) {
//        out(fromName, money);
//        if (true) throw new RuntimeException("出错了");
//        in(toName, money);
//    }

    /**
     * 外层事务
     *
     * @param fromName 从哪里转出
     * @param toName   转入到哪里
     * @param money    金额
     */
    @Transactional
    public void laoda(String fromName, String toName, int money) {
        out(fromName, money);
        if (true) throw new RuntimeException("出错了");
        xiaodi(toName,money);
    }


    /**
     * 内层事务
     *
     * @param toName   转入到哪里
     * @param money    金额
     */
    @Transactional(propagation = Propagation.MANDATORY)
    public void xiaodi(String toName, int money) {
        if (true) throw new RuntimeException("出错了");
        in(toName, money);
    }
}
